# coding: utf-8
import json

import requests
from util.log import logger, logger_alert

REPORT_URL = 'http://132.228.28.82:8888/httpServices/sendMail'

REPORT_RES = {
    "respCode": "0000",
    "respMsg": "报警",
    "result": ""
}

http = requests.Session()
headers = {'User-Agent': 'SYSTEM_1000', 'Content-Type': 'application/json'}
http.headers.update(headers)


def send_alert(header, content):
    post_data = dict()
    post_data['sender'] = 'MailSender'
    post_data['receiver'] = ["xuxuanxuan@jsoa.net"]
    post_data['subject'] = header
    post_data['body'] = content

    logger.info('发送邮件:%s' % post_data)

    error_msg = []

    try:
        rsp = http.post(
            REPORT_URL,
            json=post_data,
            timeout=3
        )
        # 状态码
        if rsp.status_code != 200:
            error_msg.append('HTTP_CODE%s' % rsp.status_code)
        else:
            # 内容解码
            rsp_data = rsp.json()
            # 解码校验是否是字典
            if not isinstance(rsp_data, dict):
                error_msg.append('结果异常%s' % rsp_data)
            else:
                error_msg.append('%s' % rsp_data)

    except requests.exceptions.Timeout:
        error_msg.append('发送超时')
    except requests.exceptions.RequestException:
        error_msg.append('发送异常')
    except json.JSONDecodeError:
        error_msg.append('解码异常')

    logger.info('邮件:%s,结果:%s' % (post_data, error_msg))
    logger_alert.info('邮件:%s,结果:%s' % (post_data, error_msg))


if __name__ == '__main__':
    send_alert('监控测试邮件标题', '监控测试邮件内容')
